/**
 * @file 统一操作 cookie
 */

import Cookies from 'js-cookie';

const defaults = {
    path: '/',
};

if (/\.[a-z]+$/i.test(window.location.hostname)) {
    defaults.domain = window.location.hostname.replace(/^[\w-]+\./, '.');
}

const cookie = Cookies.withAttributes(defaults);

// 如果是域名情况，则在删除时尝试删除主域，防止读取主域 cookie 时删除不掉导致死循环
if (/\.[a-z]+$/i.test(window.location.hostname)) {
    const { remove } = cookie;
    const domain = window.location.hostname.replace(/^[\w-]+\./, '.');
    cookie.remove = (key, options = {}) => {
        // 先删除本身域
        remove(key, options);

        // 尝试删除主域
        return remove(key, {
            ...options,
            domain,
        });
    };
}

// 如果当前是 HTTPS 环境，则默认让 cookie 走安全模式
// 但由于线上之前是 HTTP ，默认修改 secure 后会导致删除不掉之前的 cookie ，这里拦截下，兼容下之前无 secure 的
if (window.location.protocol === 'https:') {
    // cookie.defaults.secure = true;
    const {
        remove,
        set,
    } = cookie;
    cookie.set = (key, value, options = {}) => {
        set(key, value, {
            ...options,
            secure: true,
        });
    };

    cookie.remove = (key, options = {}) => {
        // 先删除正常的
        remove(key, options);

        // 再尝试删除无 secure 的
        return remove(key, {
            ...options,
            secure: false,
        });
    };
}

cookie.install = (app) => {
    app.config.globalProperties.$cookie = cookie;
};

export default cookie;
